/*******************************************************************************
 * SVN­Versioning-Information:
 * ­­­­­­­­­­­­­­­­­­­­­­­­
 * $LastChangedRevision: 6 $
 * $LastChangedBy: c.a.duevel $
 * $LastChangedDate: 2009-08-26 15:12:37 +0000 (Wed, 26 Aug 2009) $
 * $HeadURL: http://robofight.googlecode.com/svn/trunk/Server/src/de/hft_stuttgart/botwar/server/helpers/IPFinder.java $
 ******************************************************************************/
package de.hft_stuttgart.botwar.server.helpers;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author c.a.duevel@gmail.com
 */
public class IPFinder {

    static List<String> extractIPsFromNetworkInterface(final NetworkInterface ni) {
        List<String> ipList = new ArrayList<String>();
        Enumeration<InetAddress> addresses = ni.getInetAddresses();
        while (addresses.hasMoreElements()) {
            String IP = addresses.nextElement().getHostAddress();
            if (isValidIPAddress(IP)) {
                ipList.add(IP);
            }
        }
        return ipList;
    }

    public static boolean isValidIPAddress(final String address) {
        String[] addressParts = address.split("\\.");
        if (addressParts.length == 4 || addressParts.length == 5) {
            for (String s : addressParts) {
                try {
                    int num = Integer.valueOf(s);
                    if (num < 0 || num > 255) {
                        return false;
                    } else {
                        continue;
                    }
                } catch (NumberFormatException e) {
                    return false;
                }
            }
            return true;

        } else {
            return false;
        }
    }
    /**
     * @param interfaces
     * @return non LoopBack IP Addresses on this machine.
     * @throws java.net.SocketException
     */

    public static List<String> getIPs(final Enumeration<NetworkInterface>
            interfaces) throws SocketException {
        List<String> ipList = new ArrayList<String>();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            if (!ni.isLoopback()){
                ipList.addAll(extractIPsFromNetworkInterface(ni));
            }
        }
        return ipList;
    }
}
